<?php

namespace Sharks\Core\Persistence;

use Sharks\Core\Persistence\QueryBuilder\Query;

/**
 * List Model
 * 从属于Model
 *
 * 需要传入两个参数：
 * （1）$modelClass 表明的对象类
 * （2）$restrict 表明的限制条件，即某列的限制值，可传入多个，如: array('sysRoleId' => 1) or array('sysRoleId' => 1, 'availableState' => 'NORMAL');
 *
 * 使用示例：
 * <pre>
 *     class Category {
 *    
 *          public function articles() {
 *              return RelationShip::hasMany(ArticleContent::class, 'id', 'categoryId');
 *          }
 *     }
 *    
 *     $category->articles->all();
 *     $category->articles-query()->like('title', 'XXX')->lists();
 * </pre>
 */
class ListModel {

    private $restrict;
    private $modelClass;

    /** @var  缓存所有相关数据 */
    private $cacheAll;

    public function __construct($modelClass, $restrict) {
        $this->modelClass = $modelClass;
        $this->restrict = $restrict;
    }

    /**
     * 所有相关数据
     * @return array|bool
     */
    public function all() {
        if (!is_null($this->cacheAll)) {
            return $this->cacheAll;
        }
        $this->cacheAll = $this->query()->lists();
        return $this->cacheAll;
    }

    /**
     * 查询对象.已经预先设置好查询条件
     * @return $this|\ezcQuery
     */
    public function query() {
        $query = Query::createSelect()->from($this->modelClass);
        foreach ($this->restrict as $column => $value) {
            $query->eq($column, $value);
        }
        return $query;
    }
}
